package org.zpmis.api.business;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.stereotype.Service;
import org.zpmis.common.base.BaseWebService;
import org.zpmis.common.exception.BusinessException;
import org.zpmis.common.result.ResultCode;
import org.zpmis.common.utils.StringUtil;
import org.zpmis.common.utils.excel.EasyExcelUtil;
import org.zpmis.domain.label.enums.LabelEnum;
import org.zpmis.domain.label.model.Label;
import org.zpmis.domain.label.qo.LabelQo;
import org.zpmis.domain.label.qo.QueryLabelListQo;
import org.zpmis.domain.label.service.LabelService;
import org.zpmis.domain.label.vo.LabelVo;
import tk.mybatis.mapper.entity.Condition;
import tk.mybatis.mapper.entity.Example;

import java.io.IOException;
import java.time.Instant;
import java.util.List;
import java.util.stream.Collectors;

/**
 * Created with CodeGenerator
 * Description:
 * @author  Yang
 * Date: 2021-11-18
 * Time: 15:28:30
 */
@Service
@Slf4j
public class LabelWebService extends BaseWebService {
     @Reference
     private LabelService labelService;

    /**
     * 新增标签记录
     * @param labelQo
     * @throws BusinessException
     * @throws Exception
     */
    public void addLabel(LabelQo labelQo) throws BusinessException,Exception {
        labelService.save(
            Label.builder()
                    .orderNum(labelQo.getOrderNum())
                    .companyId(labelQo.getCompanyId())
                    .companyName(labelQo.getCompanyName())
                    .productName(labelQo.getProductName())
                    .labelNum(labelQo.getLabelNum())
                    .startSegment(labelQo.getStartSegment())
                    .endSegment(labelQo.getEndSegment())
                    .labelType(labelQo.getLabelType())
                    .useMode(labelQo.getUseMode())
                    .activeStatus(labelQo.getActiveStatus())
                    .generationTime(labelQo.getGenerationTime())
                    .printVoucherTime(labelQo.getPrintVoucherTime())
                    .printVoucherCompanyName(labelQo.getPrintVoucherCompanyName())
                    .applyId(labelQo.getApplyId())
                    .applyPeople(labelQo.getApplyPeople())
                    .remark(labelQo.getRemark())
                    .createTime(Instant.now().toEpochMilli())
                    .updateTime(Instant.now().toEpochMilli())
                    .isDeleted(LabelEnum.NOT_DELETE.code())
                    .build()
        );
    }

    /**
     * 修改标签卷
     * @param labelQo
     * @throws BusinessException
     * @throws Exception
     */
    public void editLabel(LabelQo labelQo) throws BusinessException,Exception {
        Long id = labelQo.getId();
        Label label = labelService.findById(id);
        if(label == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        labelService.update(
                Label.builder()
                        .id(labelQo.getId())
                        .orderNum(labelQo.getOrderNum())
                        .companyId(labelQo.getCompanyId())
                        .companyName(labelQo.getCompanyName())
                        .productName(labelQo.getProductName())
                        .labelNum(labelQo.getLabelNum())
                        .startSegment(labelQo.getStartSegment())
                        .endSegment(labelQo.getEndSegment())
                        .labelType(labelQo.getLabelType())
                        .useMode(labelQo.getUseMode())
                        .activeStatus(labelQo.getActiveStatus())
                        .generationTime(labelQo.getGenerationTime())
                        .printVoucherTime(labelQo.getPrintVoucherTime())
                        .printVoucherCompanyName(labelQo.getPrintVoucherCompanyName())
                        .applyId(labelQo.getApplyId())
                        .applyPeople(labelQo.getApplyPeople())
                        .remark(labelQo.getRemark())
                        .updateTime(Instant.now().toEpochMilli())
                        .build()
        );
    }

    /**
     * 获取标签卷详情
     * @param labelQo
     * @return
     */
    public LabelVo labelDetail(LabelQo labelQo) throws BusinessException,Exception{
        Long id = labelQo.getId();
        Label label = labelService.findById(id);
        if(label == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        return new LabelVo(label);
    }

    /**
     * 删除标签卷
     * @param labelQo
     * @throws BusinessException
     * @throws Exception
     */
    public void deleteLabel(LabelQo labelQo) throws BusinessException,Exception{
        Long id = labelQo.getId();
        Label label = labelService.findById(id);
        if(label == null){
            throw new BusinessException(ResultCode.DATA_NOT_FOUND);
        }
        label.setIsDeleted(LabelEnum.DELETED.code());
        label.setUpdateTime(Instant.now().toEpochMilli());
        labelService.update(label);
    }

    /**
     * 标签列表查询
     * @param queryLabelListQo
     * @return
     */
    public PageInfo labelList(QueryLabelListQo queryLabelListQo) {
        String companyName = queryLabelListQo.getCompanyName();
        String segment = queryLabelListQo.getSegment();
        Integer labelType = queryLabelListQo.getLabelType();
        Long startTime = queryLabelListQo.getStartTime();
        Long endTime = queryLabelListQo.getEndTime();
        Condition condition = new Condition(Label.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("isDeleted",LabelEnum.NOT_DELETE.code());
        if(labelType != null){
            criteria.andEqualTo("labelType",labelType);
        }
        if(StringUtil.isNotEmpty(companyName)){
            criteria.andLike("companyName",companyName+"%");
        }
        //TODO 范围查询有些许问题  后期根据需求优化
        if(StringUtil.isNotEmpty(segment)){
            criteria.andLessThanOrEqualTo("startSegment",segment);
            criteria.andGreaterThanOrEqualTo("endSegment",segment);
        }
        if(startTime != null && endTime != null){
            criteria.andGreaterThanOrEqualTo("generationTime",startTime);
            criteria.andLessThanOrEqualTo("generationTime",endTime);
        }
        if(startTime != null && endTime == null){
            criteria.andGreaterThanOrEqualTo("generationTime",startTime);
            criteria.andLessThanOrEqualTo("generationTime",Instant.now().toEpochMilli());
        }
        if(startTime == null && endTime != null){
            criteria.andLessThanOrEqualTo("generationTime",endTime);
        }
        PageHelper.startPage(queryLabelListQo.getPageNum(),queryLabelListQo.getPageSize());
        condition.orderBy("generationTime").desc();
        List<Label> labelList = labelService.findByCondition(condition);
        PageInfo orderPageInfo = new PageInfo<>(labelList);
        List<LabelVo> resultList = labelList.stream().map(LabelVo::new).collect(Collectors.toList());
        orderPageInfo.setList(resultList);
        return orderPageInfo;
    }

    /**
     * 导出Excel  下载Excel到本地
     * @param queryLabelListQo
     * @return
     */
    public void writeExcelLabel(QueryLabelListQo queryLabelListQo) throws IOException {
        long startDate = Instant.now().toEpochMilli();
        String companyName = queryLabelListQo.getCompanyName();
        String segment = queryLabelListQo.getSegment();
        Integer labelType = queryLabelListQo.getLabelType();
        Long startTime = queryLabelListQo.getStartTime();
        Long endTime = queryLabelListQo.getEndTime();
        Condition condition = new Condition(Label.class);
        Example.Criteria criteria = condition.createCriteria();
        criteria.andEqualTo("isDeleted",LabelEnum.NOT_DELETE.code());
        if(labelType != null){
            criteria.andEqualTo("labelType",labelType);
        }
        if(StringUtil.isNotEmpty(companyName)){
            criteria.andLike("companyName",companyName+"%");
        }
        if(StringUtil.isNotEmpty(segment)){
            criteria.andLessThanOrEqualTo("startSegment",segment);
            criteria.andGreaterThanOrEqualTo("endSegment",segment);
        }
        if(startTime != null && endTime != null){
            criteria.andGreaterThanOrEqualTo("generationTime",startTime);
            criteria.andLessThanOrEqualTo("generationTime",endTime);
        }
        if(startTime != null && endTime == null){
            criteria.andGreaterThanOrEqualTo("generationTime",startTime);
            criteria.andLessThanOrEqualTo("generationTime",Instant.now().toEpochMilli());
        }
        if(startTime == null && endTime != null){
            criteria.andLessThanOrEqualTo("generationTime",endTime);
        }
        condition.orderBy("generationTime").desc();
        List<Label> labelList = labelService.findByCondition(condition);
        List<LabelVo> resultList = labelList.stream().map(LabelVo::new).collect(Collectors.toList());
        log.info("[LabelWebService]--writeExcelLabel--->数据查询完毕,准备生成Excel并下载,结果数量:{}",resultList.size());
        try {
            EasyExcelUtil.downLoad(getResponse(), LabelEnum.labelTypeValueOfCode(labelType),LabelVo.class,resultList);
        } catch (IOException e) {
            log.error("[LabelWebService]--writeExcelLabel--->下载数据异常:",e);
        }
        log.info("[LabelWebService]--writeExcelLabel--->数据下载完成,总耗时:{}:ms",Instant.now().toEpochMilli()-startDate);
    }
}
